package com.smile67.controller;

import com.smile67.common.constant.MessageConstant;
import com.smile67.common.restult.Result;
import com.smile67.common.utils.AliOssUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 公共管理
 *
 * @author smile67
 * @version 1.0
 * @projectName ag_ai_ms
 * @package com.sky.controller
 * @className CommonController
 * @date 2023/7/14 15:14
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传，{}", file);

        try {
            //获取文件的拓展名
            String originalFilename = file.getOriginalFilename();//a.jpg
            //获取原始文件的后缀名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));// .jpg
            //构造新的文件名
            String objectName = UUID.randomUUID().toString() + extension;

            //上传到阿里云OSS服务器返回在该服务器的绝对路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            //e.printStackTrace();
            log.info("文件上传失败：{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

}

